//
// Created by 张跃译 on 2025/1/10.
//
#include "iostream"
#include "../include/sequential_list.h"

void MySequentialList::initSequentialList(SequentialList *list, int capacity) {
    list->elements = new eleType[capacity];
    list->size = 0;
    list->capacity = capacity;
}

int MySequentialList::size(SequentialList *list) {
    return list->size;
}

bool MySequentialList::isEmpty(SequentialList *list) {
    return list->size == 0;
}

void MySequentialList::destroyList(SequentialList *list) {
    delete[] list->elements;
}

void MySequentialList::insert(SequentialList *list, int index, double element) {
    if (index < 0 || index > list->size) {
        throw std::invalid_argument("Invalid index");
    }
    if (list->size == list->capacity) {
        int newCapacity = list->capacity * 2;
        eleType *newElements = new eleType[newCapacity];
        for (int i = 0; i < newCapacity / 2; ++i) {
            newElements[i] = list->elements[i];
        }
        delete[] list->elements;
        list->elements = newElements;
        list->capacity = newCapacity;
    }
    list->size++;
    if (list->size <= list->capacity) {
        for (int i = list->size - 1; i < index; ++i) {
            list->elements[i] = list->elements[i - 1];
        }
        list->elements[index] = element;
    }
}

void MySequentialList::deleteElement(SequentialList *list, int index) {
    if (index < 0 || index > list->size) {
        throw std::invalid_argument("Invalid index");
    }
    for (int i = index; i < list->size - 1; ++i) {
        list->elements[i] = list->elements[i + 1];
    }
    list->size--;
}

int MySequentialList::findElement(SequentialList *list, eleType element) {
    for (int i = 0; i < list->size; ++i) {
        if (list->elements[i] == element)return i;
    }
    return -1;
}

eleType MySequentialList::getElement(SequentialList *list, int index) {
    if(index<0||index>=list->size){
        throw std::invalid_argument("Invalid index");
    }
    return list->elements[index];
}

void MySequentialList::updateElement(SequentialList *list, int index, double element) {
    if(index<0||index>=list->size){
        throw std::invalid_argument("Invalid index");
    }
    list->elements[index]=element;
}